package com.whjz.kafka;

import com.alibaba.fastjson.JSON;
import com.whjz.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;

/**
 * 方法失败后再次调用
 * @author youkun
 * @data 2018/7/12
 */
@Slf4j
public class MethodAgain {

    public static void  KafkaMethodAgain(KafkaMethodReq kafkaMethodReq){

        if(kafkaMethodReq==null){
            log.error("kafkaMethodReq is error");
        }
        log.info("KafkaMethodAgain start params:{}", JSON.toJSONString(kafkaMethodReq));
        //获取上下文对象
        ApplicationContext applicationContext = SpringContextUtils.getApplicationContext();
        if(applicationContext==null){
            log.error(" applicationContext is null ");
        }else {
        	 //获取bean对象
            Object argObject = applicationContext.getBean(kafkaMethodReq.getClassName());
            //如果没有参数直接调用
           if(kafkaMethodReq.getParamsReqList()==null || kafkaMethodReq.getParamsReqList().size()<=0){
               try {
                   ReflectionUtils.findMethod(kafkaMethodReq.getClassName(), kafkaMethodReq.getMethod()).invoke(argObject);
               } catch (Exception e) {
                   log.error("kafka findMethod error {}",e);
               }
           }else{
               //参数
               Object argsParam[]=new Object[kafkaMethodReq.getParamsReqList().size()];
               //参数类型
               Class[] argsClass = new Class[kafkaMethodReq.getParamsReqList().size()];
               for (int i=0;i<kafkaMethodReq.getParamsReqList().size();i++){
                   argsClass[i] =  kafkaMethodReq.getParamsReqList().get(i).getTypeClass();
                   argsParam[i] = kafkaMethodReq.getParamsReqList().get(i).getParamValue();
               }
               try {
                   ReflectionUtils.findMethod(kafkaMethodReq.getClassName(), kafkaMethodReq.getMethod(), argsClass).invoke(argObject,argsParam);
               } catch (Exception e) {
                   log.error("kafka findMethod error {}",e);
               }
           }
        }
       
    }
}
